package common.remote{

	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	/**
	 * 基础远程服务对象类
	 */
	public class RemoteService extends RemoteObject {
		
		public function RemoteService(serverName:String=null) {
			super(serverName);
			this.showBusyCursor = true;
		}
		
		/**
		 * 执行远程方法
		 * @param methodName 方法名
		 * @param param 参数数组,无参数时为null
		 * @param callback 回调函数function(success:Boolean,resultObj:Object):void{}
		 */
		public function invoke(methodName:String, param:Array=null, callback:Function=null):void {
			try{
				var operation:AbstractOperation = this.getOperation(methodName);
				operation.arguments = param;
				var call:AsyncToken = operation.send();
				call.userDefinedCallback = callback;
				call.addResponder(new Responder(resultCallback, faultCallback));
			}catch(error:Error){
				trace(error.message);
			}
		}
		
		//回调成功
		private function resultCallback(event:ResultEvent):void {
			try{
				var callback:Function = event.token.userDefinedCallback as Function;
				if (callback != null) {
					callback.apply(this,[true, event.result]);
				}
			}catch(error:Error){
				trace(error.message);
			}
		}
		
		//回调失败
		private function faultCallback(event:FaultEvent):void {
			try{
				var callback:Function = event.token.userDefinedCallback as Function;
				if (callback != null) {
					callback.apply(this,[false, event.fault.toString()]);
				}
			}catch(error:Error){
				trace(error.message);
			}
		}
	}
}